package com.zeny.express.framework.file.fastdfs;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.annotation.PostConstruct;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.StorageClient1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;

import com.zeny.express.framework.file.FileStorageOperation;
import com.zeny.express.framework.file.exception.FileOperationException;

public class FileStorageOperationImpl implements FileStorageOperation {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(FileStorageOperationImpl.class);

	private Resource configFile;

	private StorageClient1 storageClient1;

	/**
	 * @param configFile
	 */
	public void setConfigFile(Resource configFile) {
		this.configFile = configFile;
	}

	@PostConstruct
	public void init() throws FileNotFoundException, IOException, MyException {
		org.csource.fastdfs.ClientGlobal.init(configFile.getURL().getPath());

		storageClient1 = new StorageClient1();
	}

	public String uploadFile(File file, String groupName, String fileName) {

		try {
			if (StringUtils.isEmpty(fileName)) {
				fileName = file.getName();
			}
			
			String ext = FilenameUtils.getExtension(fileName);
			String remoteFileName = storageClient1.upload_file1(groupName,
					file.getAbsolutePath(), ext, null);
			
			if (StringUtils.isEmpty(remoteFileName)) {
				throw new MyException("remote file is null");
			}
			int pos = remoteFileName.indexOf("/");
			if (pos < 0) {
				throw new MyException("remote file is null");
			}
			
			return remoteFileName.substring(pos + 1);

		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			throw new FileOperationException(null, null);
		}
	}

	public void deleteFile(String groupName, String remoteFileName) {

		int i = 0;
		try {
			i = storageClient1.delete_file(groupName, remoteFileName);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			throw new FileOperationException(null, null);
		}

		if (i != 0) {
			LOGGER.debug("delete file result is: " + i);
			throw new FileOperationException(null, null);
		}
	}

}
